package cn.icare.cms.controller;

import cn.icare.cms.AreaService;
import cn.icare.cms.ItemService;
import cn.icare.cms.LimitItemService;
import cn.icare.cms.ShopCartService;
import cn.icare.cms.dao.po.LimitItem;
import cn.icare.cms.dao.po.ShopCart;
import cn.icare.cms.impl.ShopCartServiceImpl;
import cn.icare.cms.model.ro.AddAreaRO;
import cn.icare.cms.model.ro.AddShopCartRO;
import cn.icare.cms.model.ro.EditAreaRO;
import cn.icare.cms.model.ro.EditShopCartRO;
import cn.icare.cms.model.vo.rest.RespMsgVO;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping(value = "/rest/personal/shopcart")
@Api(tags = "REST购物车")
public class ShopCartController extends BaseController {
    @Resource
    private ShopCartService shopCartService;
    @Resource
    private ItemService itemService;

    @Resource
    private LimitItemService limitItemService;

    private final Logger logger = LoggerFactory.getLogger(ShopCartController.class);

    private final String FALL_STRING = "请求失败,服务繁忙!";

    /**
     * URL:http://{ip}:{port}/rest/area
     * method:POST
     *
     * @param ro
     * @return
     */
    @PostMapping()
    @ApiOperation(value = "购物车商品增加", notes = "购物车商品增加")
    public ResponseEntity<RespMsgVO> createOne(@RequestBody AddShopCartRO ro, HttpServletRequest request) {
        Long memberId = this.getCurrentUserId(request);
        if (memberId <= 0) {
            return super.getRespFail("会员身份验证信息不正确");
        }

        LimitItem limitItem = this.limitItemService.getOne(ro.getItemId());
        Integer limitNum = 0;
        boolean isLimit = false;
        if (limitItem != null) {
            limitNum = 1;
            isLimit = limitItemService.checkItemIsLimitShop(limitItem, memberId);
        }


        if (isLimit) {
            return super.getRespOkFail("温馨提示：您已经参加过活动了，不能重复参加哦^～^！");
        }

        //先检查购物车是否有此商品
        ShopCart shopCart = this.shopCartService.getOne(ro.getItemId(), memberId);
        boolean result = false;
        if (shopCart != null) {
            Integer num = shopCart.getNum();
            num = num + ro.getNum();
            if (limitNum > 0 && num > limitNum) {
                num = limitNum;
                result = this.shopCartService.updateNum(shopCart.getId(), num, memberId);
                return super.getRespOkFail("温馨提示：该商品每人限购1件，不能重复添加^～^！");
            }
            result = this.shopCartService.updateNum(shopCart.getId(), num, memberId);
        } else {
            BigDecimal currentPrice = itemService.getItemPrice(ro.getItemId());
            Long id = this.shopCartService.createOne(ro, memberId, currentPrice);
            if (id >= 0) {
                result = true;
            }
        }
        if (result) {
            return super.getRespOk(result);
        } else {
            return super.getRespFail();
        }
    }

    /**
     * URL:http://{ip}:{port}/rest/area
     * method:PUT
     *
     * @param ro
     * @return
     */
    @PutMapping()
    @ApiOperation(value = "修改商品数量", notes = "修改商品数量")
    public ResponseEntity<RespMsgVO> updateOne(@RequestBody EditShopCartRO ro, HttpServletRequest request) {


        Long memberId = this.getCurrentUserId(request);
        if (memberId <= 0) {
            return super.getRespFail("会员身份验证信息不正确");
        }
        ShopCart shopCart = shopCartService.getOneById(ro.getId());
        if (shopCart != null) {
            LimitItem limitItem = this.limitItemService.getOne(shopCart.getItemid());
            if (limitItem != null) {
                return super.getRespOkFail("温馨提示：该商品每人限购1件，不能重复添加^～^！");
            }

            if (this.shopCartService.updateNum(ro.getId(), ro.getNum(), memberId)) {
                return super.getRespOk();
            } else {
                return super.getRespFail();
            }
        }
        return super.getRespOkFail("购物车商品数据有变化，请刷新购物车");
    }

    /**
     * URL:http://{ip}:{port}/rest/area/{id}
     * method:DELETE
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除商品", notes = "删除商品")
    public ResponseEntity<RespMsgVO> deleteOne(@PathVariable("id") Long id, HttpServletRequest request) {

        Long memberId = this.getCurrentUserId(request);
        if (memberId <= 0) {
            return super.getRespFail("会员身份验证信息不正确");
        }
        if (this.shopCartService.deleteOne(id, memberId)) {
            return super.getRespOk();
        } else {
            return super.getRespFail();
        }
    }

    /**
     * URL:http://{ip}:{port}/rest/area?ids={ids}
     * method:DELETE
     *
     * @param ids
     * @return
     */
    @DeleteMapping()

    @ApiOperation(value = "批量删除商品", notes = "批量删除商品")
    public ResponseEntity<RespMsgVO> deleteBatch(@RequestParam("ids") List<Long> ids, HttpServletRequest request) {
        Long memberId = this.getCurrentUserId(request);
        if (memberId <= 0) {
            return super.getRespFail("会员身份验证信息不正确");
        }
        if (this.shopCartService.deleteBatch(ids, memberId)) {
            return super.getRespOk();
        } else {
            return super.getRespFail();
        }
    }


    /**
     * URL:http://{ip}:{port}/rest/area?args={args}
     * method:GET
     *
     * @return
     */
    @GetMapping()
    @ApiOperation(value = "查询会员购物车商品列表", notes = "查询会员购物车商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "areaId", value = "区域id", required = true, paramType = "query", dataTypeClass = Long.class),
    })
    public ResponseEntity<RespMsgVO> getList(Long areaId, HttpServletRequest request) {
        Long memberId = this.getCurrentUserId(request);
        if (memberId <= 0) {
            return super.getRespFail("会员身份验证信息不正确");
        }
        //TODO 第一版临时只有一个仓库的版本，以后多区域多仓库需要注释掉下面这行代码
        areaId = changeStoreAreaId(areaId);
        return super.getRespOk(this.shopCartService.getList(memberId, areaId));
    }

    //#region fallback methods
    //#endregion

}
